from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
from django.utils import timezone
from django.conf import settings

class FoodCategory(models.Model):
    name = models.CharField(verbose_name='美食分类',max_length=100, unique=True)
    description = models.TextField(blank=True)
    def __str__(self):
        return self.name

from xpinyin import Pinyin
import re
class FoodItem(models.Model):
    name = models.CharField(verbose_name='美食名',max_length=200)
    name_pinyin = models.CharField('全拼', max_length=512, editable=False, db_index=True, blank=True)
    name_py_abbr = models.CharField('简拼', max_length=128, editable=False, db_index=True, blank=True)
    category = models.ForeignKey(FoodCategory, on_delete=models.CASCADE,verbose_name='所属分类')
    description = models.TextField(verbose_name='美食描述',blank=True)
    tags = models.ManyToManyField(to='Tag',verbose_name='所属标签',max_length=300, blank=True,related_name='food_items')  # 用逗号分隔的标签
    created_at = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='创建者')

    def save(self, *args, **kwargs):
        self.name_pinyin = Pinyin().get_pinyin(self.name, '')
        self.name_py_abbr = ''.join([
            w[0] for w in re.findall(r'[a-z]+', self.name_pinyin)
        ])
        super().save(*args, **kwargs)

    def __str__(self):
        return self.name

    def get_tag_names(self):
        """获取标签名称列表"""
        return list(self.tags.values_list('name', flat=True))

    def get_tag_colors(self):
        """获取标签颜色映射"""
        return {tag.name: tag.color for tag in self.tags.all()}

class DailyFoodRecord(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    date = models.DateField(default=timezone.now)
    breakfast = models.ForeignKey(FoodItem, on_delete=models.SET_NULL,
                                  null=True, blank=True, related_name='breakfast_records',verbose_name='早餐')
    lunch = models.ForeignKey(FoodItem, on_delete=models.SET_NULL,
                              null=True, blank=True, related_name='lunch_records',verbose_name='午餐')
    dinner = models.ForeignKey(FoodItem, on_delete=models.SET_NULL,
                               null=True, blank=True, related_name='dinner_records',verbose_name='晚餐')
    snacks = models.ManyToManyField(FoodItem, blank=True, related_name='snack_records',verbose_name='零食')
    notes = models.TextField(blank=True)
    tags = models.ManyToManyField(to='Tag',blank=True,related_name='daily_records')
    class Meta:
        unique_together = ['user', 'date']

    def __str__(self):
        return f"{self.user.username} - {self.date}"


class UserPreference(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    preferred_categories = models.ManyToManyField(FoodCategory, blank=True,verbose_name='首选类别')
    disliked_foods = models.ManyToManyField(FoodItem, blank=True,verbose_name='不喜欢的食物')
    dietary_restrictions = models.TextField(blank=True,verbose_name='饮食限制')
    preferred_tags = models.ManyToManyField(to='Tag', blank=True, related_name='preferred_by_users')
    def __str__(self):
        return f"{self.user.username}的偏好设置"


class Tag(models.Model):
    """标签模型"""
    name = models.CharField(max_length=50, unique=True, verbose_name="标签名")
    color = models.CharField(max_length=7, default='#6c757d', verbose_name="标签颜色")  # Bootstrap颜色代码
    description = models.TextField(blank=True, verbose_name="标签描述")
    parent = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True, related_name='children', verbose_name='父级标签')
    created_at = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)

    class Meta:
        verbose_name = "标签"
        verbose_name_plural = "标签"
        ordering = ['name']

    def __str__(self):
        return self.name

    def get_food_count(self):
        """获取使用此标签的食物数量"""
        return self.food_items.count()


class Recipe(models.Model):
    """做菜指南模型"""
    DIFFICULTY_CHOICES = [
        ('easy', '简单'),
        ('medium', '中等'),
        ('hard', '困难'),
    ]
    
    COOKING_TIME_CHOICES = [
        ('15', '15分钟以内'),
        ('30', '30分钟以内'),
        ('60', '1小时以内'),
        ('120', '2小时以内'),
        ('240', '4小时以内'),
    ]
    
    name = models.CharField(max_length=200, verbose_name="菜品名称")
    description = models.TextField(verbose_name="菜品描述", blank=True)
    difficulty = models.CharField(max_length=10, choices=DIFFICULTY_CHOICES, default='medium', verbose_name="难度")
    cooking_time = models.CharField(max_length=10, choices=COOKING_TIME_CHOICES, default='30', verbose_name="制作时间")
    servings = models.PositiveIntegerField(default=2, verbose_name="份数")
    category = models.ForeignKey(FoodCategory, on_delete=models.CASCADE, verbose_name="菜品分类")
    tags = models.ManyToManyField(Tag, blank=True, verbose_name="相关标签")
    image = models.ImageField(upload_to='recipe_images/', blank=True, null=True, verbose_name="菜品图片")
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="创建者")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        verbose_name = "做菜指南"
        verbose_name_plural = "做菜指南"
        ordering = ['-created_at']
    
    def __str__(self):
        return self.name
    
    def get_total_cooking_time(self):
        """获取总制作时间"""
        return dict(self.COOKING_TIME_CHOICES).get(self.cooking_time, '未知')
    
    def get_difficulty_display_cn(self):
        """获取中文难度显示"""
        return dict(self.DIFFICULTY_CHOICES).get(self.difficulty, '未知')


class RecipeIngredient(models.Model):
    """菜品食材模型"""
    UNIT_CHOICES = [
        ('g', '克'),
        ('kg', '千克'),
        ('ml', '毫升'),
        ('l', '升'),
        ('个', '个'),
        ('根', '根'),
        ('片', '片'),
        ('瓣', '瓣'),
        ('勺', '勺'),
        ('茶匙', '茶匙'),
        ('汤匙', '汤匙'),
        ('杯', '杯'),
        ('适量', '适量'),
    ]
    
    recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='ingredients', verbose_name="菜品")
    name = models.CharField(max_length=100, verbose_name="食材名称")
    amount = models.CharField(max_length=50, verbose_name="用量")
    unit = models.CharField(max_length=10, choices=UNIT_CHOICES, default='适量', verbose_name="单位")
    notes = models.CharField(max_length=200, blank=True, verbose_name="备注")
    order = models.PositiveIntegerField(default=0, verbose_name="排序")
    
    class Meta:
        verbose_name = "菜品食材"
        verbose_name_plural = "菜品食材"
        ordering = ['order', 'id']
    
    def __str__(self):
        return f"{self.name} {self.amount}{self.unit}"


class RecipeStep(models.Model):
    """制作步骤模型"""
    recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='steps', verbose_name="菜品")
    step_number = models.PositiveIntegerField(verbose_name="步骤序号")
    title = models.CharField(max_length=200, verbose_name="步骤标题")
    description = models.TextField(verbose_name="步骤描述")
    cooking_time = models.CharField(max_length=50, blank=True, verbose_name="此步骤用时")
    heat_level = models.CharField(max_length=50, blank=True, verbose_name="火候")
    image = models.ImageField(upload_to='recipe_step_images/', blank=True, null=True, verbose_name="步骤图片")
    tips = models.TextField(blank=True, verbose_name="小贴士")
    
    class Meta:
        verbose_name = "制作步骤"
        verbose_name_plural = "制作步骤"
        ordering = ['step_number']
    
    def __str__(self):
        return f"{self.recipe.name} - 第{self.step_number}步: {self.title}"


# 直接映射数据库中的caipu表
class Caipu(models.Model):
    """菜谱模型，直接映射数据库中的caipu表"""
    id = models.IntegerField(primary_key=True)
    title = models.CharField(max_length=200, verbose_name="菜名")
    thumb = models.TextField(blank=True, verbose_name='菜品照片')
    desc = models.TextField(blank=True, verbose_name="介绍")
    yl = models.TextField(blank=True, verbose_name="材料")
    fl = models.TextField(blank=True, verbose_name='分量')
    steptext = models.TextField(blank=True, verbose_name="做法")
    steppic = models.TextField(blank=True, verbose_name="作法步骤照片")

    
    class Meta:
        # 不创建表，直接使用现有的caipu表
        managed = False
        db_table = 'caipu'
    
    def __str__(self):
        return self.title
    
    def get_ingredients_list(self):
        """获取材料列表"""
        if self.yl or self.fl:
            materials = [m.strip() for m in self.yl.split('#') if m.strip()]
            amounts = [a.strip() for a in self.fl.split('#') if a.strip()]

            return [f'{m} {amounts[i] if i < len(amounts) else ""}'.strip()
                    for i, m in enumerate(materials)]
        else:
            return []
    
    def get_steps_list(self):
        """获取步骤列表"""
        if self.steptext:
            return [step.strip() for step in self.steptext.split('#') if step.strip()]
        else:
            return []

    def get_images_list(self):
        """获取图片URL列表"""
        if self.thumb:
            return [image.strip() for image in self.thumb.split('#') if image.strip()]
        else:
            return []
    
    def get_steppic_list(self):
        """获取步骤图片URL列表"""
        if self.steppic:
            return [image.strip() for image in self.steppic.split('#') if image.strip()]
        else:
            return []
